package com.guoqing.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.StringUtils;

import java.beans.PropertyDescriptor;
import java.util.*;

/**
 * @author guoQ.z
 * @date 2021/1/20 9:41
 * TODO
 */
@Slf4j
public class BeanCommon {

    public static void convertSkipNull(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullProperty(source));
    }

    public static String[] getNullProperty(Object source) {
        BeanWrapper wrapper = new BeanWrapperImpl(source);
        PropertyDescriptor[] propertyDescriptors = wrapper.getPropertyDescriptors();
        Set<String> set = new HashSet<>();
        for (PropertyDescriptor property : propertyDescriptors) {
            Object value = wrapper.getPropertyValue(property.getName());
            if (Objects.isNull(value)) {
                set.add(property.getName());
            }
        }
        return StringUtils.toStringArray(set);
    }

    public static <T> T convert(Object sourceBean, Class<T> clazz) {
        try {
            T t = clazz.newInstance();
            BeanUtils.copyProperties(sourceBean, t);
            return t;
        } catch (Exception ex) {
            log.error("对象转换异常，message:{}", ex.getMessage());
            throw new RuntimeException("对象转换异常," + ex.getMessage());
        }
    }

    public static <T> List<T> convertList(List<?> sourceList, Class<T> clazz) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return Lists.newArrayList();
        }
        String jsonString = JSON.toJSONString(sourceList);
        return JSON.parseArray(jsonString, clazz);
    }

    public static Map<String, String> convertMap(Object obj) {
        String jsonString = JSON.toJSONString(obj);
        return JSON.parseObject(jsonString, new TypeReference<Map<String, String>>() {
        });
    }

}
